﻿using System.Net.Http;
using System.Web.Http.Filters;

namespace HuntingFishGame.CustomerApi
{
    /// <summary>
    /// [Web API] 如何让 Web API 统一回传格式以及例外处理 http://it.zhaozhao.info/archives/63240
    /// config.Filters.Add(new ApiResultAttribute());
    /// </summary>
    public class ApiResultAttribute : System.Web.Http.Filters.ActionFilterAttribute
    {
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnActionExecuted(actionExecutedContext);

            ApiResultModel result = new ApiResultModel();
            // 取得由 API 返回的状态代码
            result.Status = actionExecutedContext.ActionContext.Response.StatusCode;
            // 取得由 API 返回的资料
            result.Data = actionExecutedContext.ActionContext.Response.Content.ReadAsAsync<object>().Result;
            // 重新封装回传格式
            actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(result.Status, result);
        }
    }
}
